import { login } from '@/api/user'
import { apiSysPower, apiUserLoginToken } from '@/api/system'
import { setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  userInfo: ''
}

const mutations = {
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
    localStorage.setItem('feijiu_user_info', JSON.stringify(userInfo))
    localStorage.setItem('feijiu_user_id', userInfo.id)
    localStorage.setItem('feijiu_user_uid', userInfo.uid)
    localStorage.setItem('feijiu_user_name', userInfo.name)
    setToken(userInfo.token)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password })
        .then((response) => {
          const { result } = response
          commit('setUserInfo', result)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 使用其他账号登录
  otherUserlogin({ commit }, id) {
    return new Promise((resolve, reject) => {
      apiUserLoginToken({ id })
        .then((response) => {
          const { data } = response
          commit('setUserInfo', data)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 获取菜单权限
  getMenu({ commit, state }) {
    return new Promise((resolve, reject) => {
      apiSysPower()
        .then((res) => {
          const { data } = res
          localStorage.setItem('feijiu_user_menu', JSON.stringify(data))
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      localStorage.removeItem('feijiu_user_id')
      localStorage.removeItem('feijiu_user_uid')
      localStorage.removeItem('feijiu_user_name')
      localStorage.removeItem('feijiu_user_menu')
      removeToken() // must remove  token  first
      resetRouter()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
